package com.ycp.poi;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ycp
 * @version V1.0
 * @Description
 * @date 2018/10/21 10:20 PM
 */
public class XlsReader {
    
    public static List<TestData> readFromXlsFile(String path, String keywords)  {
        try {
            // 创建对Excel工作簿文件的引用
            HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(path));
    
            HSSFSheet sheet = workbook.getSheetAt(0);
            List<TestData> result = new ArrayList<>();
            for(int i = 1; i < sheet.getLastRowNum(); i++) {
                HSSFRow row = sheet.getRow(i);
                TestData testData = new TestData();
                testData.setId((int)(row.getCell(4).getNumericCellValue()));
                testData.setType(row.getCell(5).getStringCellValue());
                testData.setQuestion(row.getCell(6).getCellType() == 0 ? String.valueOf(row.getCell(6).getNumericCellValue()) : row.getCell(6).getStringCellValue());
                testData.setAns1(row.getCell(7).getCellType() == 0 ? String.valueOf(row.getCell(7).getNumericCellValue()) : row.getCell(7).getStringCellValue());
                testData.setAns2(row.getCell(8).getCellType() == 0 ? String.valueOf(row.getCell(8).getNumericCellValue()) : row.getCell(8).getStringCellValue());
                testData.setAns3(row.getCell(9).getCellType() == 0 ? String.valueOf(row.getCell(9).getNumericCellValue()) : row.getCell(9).getStringCellValue());
                testData.setAns4(row.getCell(10).getCellType() == 0 ? String.valueOf(row.getCell(10).getNumericCellValue()) : row.getCell(10).getStringCellValue());
                String ans11 = row.getCell(11).getCellType() == 0 ? String.valueOf(row.getCell(11).getNumericCellValue()) : row.getCell(11).getStringCellValue();
                String ans16 = row.getCell(16).getCellType() == 0 ? String.valueOf(row.getCell(16).getNumericCellValue()) : row.getCell(16).getStringCellValue();
                String rightAns = (ans11 == null || "".equals(ans11) )? ans16 : ans11;
                testData.setRightAns(rightAns);
                if(testData.getType().equals(keywords)) {
                    result.add(testData);
                }
            }
            return result;
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
